import { FieldTypeMappingEnum } from '@model/enum/FieldMappingEnum'
/* component */
import { FormQualityRuleViewProps } from '@src/component/form/components/FormQualityRuleField/FormQualityRuleView'
/* entity */
import Field from '@model/entity/Field'
import { QualityRuleOriginal } from '@model/entity/QualityRule'
/* model */
import { getGroupsFields } from '@src/component/form/components/FormQualityRuleField/FormQualityRuleModel'
/* service */
import { convertQualityRuleRemoteDataToFormQualityRuleFieldValue } from '@service/QualityRuleService'
import { getFieldDisplayName, getFieldIsNull, getFieldSetting } from '@service/FieldService'
/* vue */
import { computed, ComputedRef } from 'vue'
/* util */
import { isEmpty } from '@src/util/type'

export type useQualityRuleFormReturnValue = [ComputedRef<Field[]>, ComputedRef<Field>, ComputedRef<Record<string, any>>]

export function useQualityRuleFormGroupFields(field: Field | undefined) {
  // 分组字段子字段列表
  return (
    computed<Field[]>(() => {
      let displayName: string = getFieldDisplayName(field)
      let isNull: number = getFieldIsNull(field)
      let setting: object = getFieldSetting(field)
      
      return getGroupsFields(displayName, isNull, setting)
    })
  )
}

export function useQualityRuleForm(props: FormQualityRuleViewProps): useQualityRuleFormReturnValue {
  // 分组字段子字段列表
  const groupFields = useQualityRuleFormGroupFields(props.field)
  
  // 质保规则字段
  const qualityRuleField = computed<Field>(() => {
    return {
      ...(props.field || { fieldName: FieldTypeMappingEnum.QualityRule, formType: FieldTypeMappingEnum.QualityRule }),
      groupFields: groupFields.value
    }
  })
  
  // 质保规则字段值
  const qualityRuleFieldValue = computed<Record<string, any>>(() => {
    const value: Record<string, any> = (isEmpty(props.value) ? props.originValue : props.value) || {}
    return convertQualityRuleRemoteDataToFormQualityRuleFieldValue(value as QualityRuleOriginal) 
  })
  
  return [groupFields, qualityRuleField, qualityRuleFieldValue]
}
